package com.mymail.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.mymail.entity.File;
import com.mymail.entity.Mail;

public class FileDAO extends DAOImp implements DAO {

	public ArrayList<File> getFilesByMail(Mail mail) {
		String sql = "select * from `file` where mail_id=?";
		return findArray(sql, new Object[] { mail.getId() });
	}

	public boolean addNew(Object obj) {
		File file = (File) obj;
		String sql = "insert into `file` (mail_id,file_name,file_form,"
				+ "file_savename,file_path,file_size) values (?,?,?,?,?,?)";
		int i = insert(sql, new Object[] { file.getMail(), file.getName(),
				file.getForm(), file.getSaveName(), file.getPath(),
				file.getSize() });
		if (i > 0) {
			file.setId(i);
			return true;
		}
		return false;
	}

	public boolean delete(Object obj) {
		File file = (File) obj;
		String sql = "delete from `file` where file_id=?";
		return exe(sql, new Object[] { file.getId() });
	}

	public boolean getByID(Integer id, Object obj) {
		File file = (File) obj;
		String sql = "select * from `file` where file_id=?";
		return findOne(sql, new Object[] { file.getId() }, file);
	}

	public boolean toDatabase(Object obj) {
		File file = (File) obj;
		if (file.getId() == null) {
			return addNew(file);
		} else {
			return update(file);
		}
	}

	public boolean update(Object obj) {
		File file = (File) obj;
		String sql = "update `file` set file_name=?,file_form=?,"
				+ "file_savename=?,file_path=?,file_size=?  where file_id=?";
		return exe(sql, new Object[] { file.getName(), file.getForm(),
				file.getSaveName(), file.getPath(), file.getSize(),
				file.getId() });
	}

	protected Object getEntity(ResultSet result) throws SQLException {
		File file = new File();
		setAtribute(result, file);
		return file;
	}

	protected void setAtribute(ResultSet result, Object obj)
			throws SQLException {
		File file = (File) obj;
		file.setId(result.getInt("file_id"));
		file.setMail(result.getInt("mail_id"));
		file.setName(result.getString("file_name"));
		file.setForm(result.getString("file_form"));
		file.setSaveName(result.getString("file_savename"));
		file.setPath(result.getString("file_path"));
		file.setSize(result.getInt("file_size"));
	}

}
